import 'dart:convert';
import 'package:agro_sklad_new/feature/data/model/stock_model.dart';
import 'package:http/http.dart' as http;
import '../../../../core/errors/exceptions.dart';

abstract class StockRemoteDataSource {
  /// Calls the https://rickandmortyapi.com/api/character/?page=1 endpoint.
  ///
  /// Throws a [ServerException] for all error codes.
  Future<List<StockModel>> getAllStock();
}

class StockRemoteDataSourceImpl implements StockRemoteDataSource {
  final http.Client client;


  StockRemoteDataSourceImpl({required this.client});

  @override
  Future<List<StockModel>> getAllStock() async {
    String url = 'https://agropulse.st-inv.ru/agsklad-stage/?db=agsklad_test';
    print("url ============ $url");
    final response = await client.post(
      Uri.parse(url),
      body: {
        "jsonrpc": "2.0",
        "method": "stock",
        "params": ""
      },
      headers: {'Accept': 'application/json', 'Accept-Charset': 'utf-8'},
    );
    if (response.statusCode == 200) {

      var data = json.decode(response.body);
      // print(data['result']);
      List<StockModel> res = (data['result']).map((stock) => StockModel.fromJson(stock)).toList();
      print (res.toString());
      return res;
    } else {
      throw ServerException();
    }
  }
}